#include <iostream>
#include <fstream>
#include <vector>
#include <pthread.h>
#include <stdlib.h>//srand(),rand()

using namespace std;

const int BUFSIZE = 5;

std::vector<int> buf1(BUFSIZE, 0);
std::vector<int> buf2(BUFSIZE, 0);

/*将数据从内存向磁盘搬运*/
pthread_cond_t buffull = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;


void *consumer(void *p)
{
	fstream tmpfile ("tmp.data", ios::out /*| ios::app*/ | ios::binary );
	for (;;) {
		pthread_mutex_lock(&lock);
		while (1)
		{
			cout << "wait ..." << endl;
			pthread_cond_wait(&buffull, &lock);
		}
		
		//一次性向磁盘写入BUFSIZE个元素
		for (vector<int>::iterator it = buf1.begin(); it != buf1.end(); it++)
		{
			tmpfile << *it << endl;
		}

		pthread_mutex_unlock(&lock);
		cout << "Consume " << endl;
		sleep(rand() % 3);
	}
}


int main ()
{
	pthread_t cid;

	srand(time(NULL));
	vector<int>::iterator it;
	pthread_create(&cid, NULL, consumer, NULL);

	bool switchbuf = false;
	for (;;) {
		int tmp = rand();
		pthread_mutex_lock(&lock);
		cout << "Produce " << endl;

		//一次性向内存写入BUFSIZE个元素
		if ( switchbuf )
		{
			for (it = buf2.begin(); it != buf2.end(); it++)
			{
				*it = tmp;
			}
			switchbuf = false;
		}
		else
		{
			for (it = buf1.begin(); it != buf1.end(); it++)
			{
				*it = tmp;
			}
			switchbuf = true;
		}

		pthread_mutex_unlock(&lock);
		pthread_cond_signal(&buffull);
		sleep(rand() % 3);
	}

	pthread_join(cid, NULL);

	return 0;
}
